package com.wit.witmg.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Base64;


public class HMAC_SHA1 {
	public static String getSinal(String data, String passwrod )
	{
		String key=md5(passwrod);
		byte[] hmac = null;
		try {
			hmac = hashHmac(data,key);
		} catch (InvalidKeyException e) {
			 
			e.printStackTrace();
		} catch (SignatureException e) {
		 
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			 
			e.printStackTrace();
		}
	    String sign = Base64.getEncoder().encodeToString(hmac);
	    return sign;
	}
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is unsupported", e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MessageDigest不支持MD5Util", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public static byte[] hashHmac(String data, String key)
            throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return mac.doFinal(data.getBytes());
    }
}

